package com.jfm.jfmc.core.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import com.jfm.jfmc.core.constants.DeviceConstants;
import com.jfm.jfmc.core.constants.TemplateConstants;
import com.jfm.jfmc.core.icc.CollectTaskManage;
import com.jfm.jfmc.core.service.ICollectTemplateService;
import com.jfm.jfmm.collector.driver.ACollectorDriver;
import com.jfm.jfmm.collector.entity.collect.CollectParam;
import com.jfm.jfmm.collector.entity.device.Device;
import com.jfm.jfmm.collector.entity.template.CollectTemplate;
import com.jfm.jfmm.collector.enums.CollectorProtocol;
import com.jfm.jfmm.utils.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author DYang
 * @since 2024-10-13 22:32
 */
@Slf4j
@Service
public class CollectTemplateServiceImpl implements ICollectTemplateService {

    /**
     * 缓存设备到本地，只初始化一次
     */
    private static List<Device> devices = null;
    /**
     * 缓存模板到本地，只初始化一次
     */
    private static Map<String, CollectTemplate> templates = null;


    @Override
    public synchronized List<Device> initDevices() {
        if (CollectionUtil.isEmpty(devices)) {
            synchronized (this) {
                List<Path> pathList = ResourceUtil.getAllFileInDir(DeviceConstants.DEVICE_CONFIG_DIR, DeviceConstants.DEVICE_CONFIG_SUFFIX);
                if (pathList == null) {
                    log.error("未找到设备配置文件");
                    return null;
                }
                List<Dict> dicts = ResourceUtil.ymlToJSON(pathList);
                List<Device> list = Device.buildDevices(dicts);
                if (list != null) {
                    devices = list;
                }
                return devices;
            }
        }
        return devices;
    }

    @Override
    public synchronized Map<String, CollectTemplate> initTemplate() {
        if (CollectionUtil.isEmpty(templates)) {
            synchronized (this) {
                List<Path> pathList = ResourceUtil.getAllFileInDir(TemplateConstants.TEMPLATE_CONFIG_DIR, TemplateConstants.TEMPLATE_CONFIG_SUFFIX);
                if (pathList == null) {
                    log.error("未找到模板配置文件");
                    return null;
                }
                Map<String, Dict> dictMap = ResourceUtil.ymlToJSONMap(pathList);
                if (dictMap == null) return null;

                Map<String, CollectTemplate> templates = CollectTemplate.buildTemplates(dictMap);
                if (templates != null) {
                    CollectTemplateServiceImpl.templates = templates;
                }
            }
        }
        return templates;
    }

    @Override
    public List<CollectParam> buildCollectParam() {
        this.initDevices();
        this.initTemplate();
        if (CollectionUtil.isEmpty(devices) || CollectionUtil.isEmpty(templates)) {
            log.error("设备或模板未初始化成功");
            return null;
        }
        List<CollectParam> params = new ArrayList<>();
        for (Device device : devices) {
            List<CollectParam> paramList = this.buildCollectParam(device);
            if (paramList != null) {
                params.addAll(paramList);
            }
        }
        return params;
    }

    /**
     * 构建采集参数
     * @param device 设备信息
     * @return
     */
    private List<CollectParam> buildCollectParam(Device device) {
        String[] templateNames = device.getTemplates();
        String[] protocolNames = device.getProtocol();
        if (templateNames == null || templateNames.length == 0 || protocolNames == null || protocolNames.length == 0){
            log.error("设备未配置模板或未启用协议，{}",device);
            return null;
        }
        List<CollectParam> params = new ArrayList<>();
        // 加载使用的模板
        for (String templateName : templateNames) {
            CollectTemplate template = templates.get(templateName);
            if (template == null) {
                log.error("模板未找到，{}",templateName);
                continue;
            }
            // 根据启用的协议来加载参数
            for (String protocolName : protocolNames) {
                CollectorProtocol protocol = CollectorProtocol.getByProtocol(protocolName);
                if (protocol == null) {
                    log.error("协议未找到，{}",protocolName);
                    continue;
                }
                // 设备、模板、协议绑定成功，构建采集参数
                ACollectorDriver<?,?> driver = ACollectorDriver.getDriver(protocol);
                // 构建采集参数
                List<CollectParam> collectParams = driver.buildCollectParam(device, template);
                if (collectParams != null) {
                    params.addAll(collectParams);
                }
            }
        }

        return params;
    }

    @Override
    public void buildCollectJob() {
        // 构建采集参数
        List<CollectParam> collectParams = this.buildCollectParam();
        if (CollectionUtil.isEmpty(collectParams)) {
            return;
        }
        // 构建采集任务
        CollectTaskManage.init(collectParams);
    }

}
